using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using Microsoft.SharePoint;

namespace ARF.Web.Utility
{
    public class SharePointXmlUrlResolver : XmlUrlResolver
    {
        protected string _rootUri;
        protected string _relativeUri;

        public SharePointXmlUrlResolver(string rootUri, string relativeUri)
        {
            _rootUri = rootUri;
            _relativeUri = relativeUri;
        }

        public override Uri ResolveUri(Uri baseUri, string relativeUri)
        {
            if (relativeUri.StartsWith("/"))
                return new Uri(_rootUri + relativeUri);
            else
                return new Uri(_rootUri + _relativeUri + relativeUri);
        }

        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
        {
            try
            {
                string sRelativeUrl = absoluteUri.ToString().Substring(_rootUri.Length);
                SPFile oFile = SPContext.Current.Site.RootWeb.GetFile(sRelativeUrl);

                return oFile.OpenBinaryStream(SPOpenBinaryOptions.SkipVirusScan);
            }
            catch (Exception ex)
            {
                Log.Trace("Failed to get entity");
                Log.Trace(ex);
            }

            return null;
        }
    }
}
